package app.auto.runner.base.utility;


import android.webkit.WebView;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.util.List;

import app.auto.AndroidInstance;
import app.auto.runner.base.framework.CrashHandler;
import app.auto.runner.base.intf.json.JsonToMapUtils;

/**
 * Created by hp on 2018/3/11.
 */

public class WriteFileUtil extends AndroidInstance {


    public void demo(String path,Object listorjsonlist) {
        WriteFileUtil.get(WriteFileUtil.class, getContext()).setCsvpath(StorageUtil.getPrimaryStoragePath(getContext())).setJsonlist("").writeCsv();
    }

    String csvpath;
    List list;
    String jsonlist;

    public WriteFileUtil setCsvpath(String csvpath) {
        this.csvpath = csvpath;
        return this;
    }

    public WriteFileUtil setList(List list) {
        this.list = list;
        return this;
    }

    public WriteFileUtil setJsonlist(String jsonlist) {
        this.jsonlist = jsonlist;
        return this;
    }

    public WriteFileUtil writeCsv() {
        if (list == null && jsonlist == null) {
            throw new RuntimeException("param list or jsonlist = null ");
        }
        if (csvpath == null) {
            throw new RuntimeException("csvpath = null");
        }
        if (list == null) {
            list = JsonToMapUtils.jsontoList(jsonlist);
        }
        StringBuffer csv = WriteFileUtil.writeTxtToCsv(CsvUtil.get(CsvUtil.class, getContext()).toCsv(list), "&&");
        WriteFileUtil.writeTxtToFile(csv.toString(), csvpath);
        return this;
    }

    public void initData() {
        String filePath = "/sdcard/Test/";
        String fileName = "log.txt";

        writeTxtToFile("txt content", filePath, fileName);
    }

    public static StringBuffer writeTxtToCsv(String strcontent, String seperatotor) {

        BufferedWriter bw = null;
        try {
//       写文件
            StringWriter sw;
            bw = new BufferedWriter(sw = new StringWriter());
            //读文件
            String[] ls = strcontent.split(seperatotor);

            int i = 0;
            String line = null;
            while ((line = ls[i]) != null) {

                String myText = ls[i];
//          int value = Integer.parseInt(last);//如果是数值，可以转化为数值
//          System.out.println(last);

                // 添加新的数据行
                bw.write(myText);
                bw.newLine();
                if (i < ls.length - 1) {
                    i++;
                } else {
                    break;
                }
            }
            return sw.getBuffer();
        } catch (Exception e) {
            CrashHandler.errorDialog(e);
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static void writeTxtToFile(String strcontent, String filePath) {
        new File(filePath).getParentFile().mkdirs();
        if(!new File(filePath).exists()){
            try {
                new File(filePath).createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        writeTxtToFile(strcontent, new File(filePath).getParent(), new File(filePath).getName());
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
//        if (TextUtils.isEmpty(strcontent)) {
//            return;
//        }
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + "/" + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
//            if (file.exists()) {
//                file.delete();
//            }

            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(0);
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + "/" + fileName);
            if (file.exists()) {
                file.delete();
            }
            if (!file.exists()) {
//                file.delete();
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
        }
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }
}
